package com.sbw.springboot.demo.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;

/**
 * @Author: sangbowei
 * @Description: 缓存配置
 * @Date: Created in  16:09 2017\12\11 0011
 **/
@Configuration
@EnableCaching
public class CacheConfiguration extends CachingConfigurerSupport {

    /*定义缓存数据 key 生成策略的bean
   包名+类名+方法名+所有参数
   */
    @Bean
    @Override
    public KeyGenerator keyGenerator(){

        /**
         * java.lang.ClassCastException: org.springframework.cache.interceptor.SimpleKey cannot be cast to java.lang.String
         * 必须复写此方法，可解决上述报错
         */
        KeyGenerator keyGenerator =  new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder builder = new StringBuilder();
                builder.append(target.getClass().getName());
                builder.append(method.getName());
                for (Object obj : params) {
                    String objStr = obj.toString();
                    builder.append(objStr);
                }
                return builder.toString();
            }
        };
        return keyGenerator;


    }

}